//
//  MBLookForPasswordController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/22.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBLookForPasswordController.h"
#import "MBLookForPasswordLastController.h"
#import "MBNavController.h"
#import "NSString+PJR.h"
#import "ErrorMessage.h"
#import "NSString+MD5String.h"
@interface MBLookForPasswordController () {
    int timeout;

     NSString        *codeStr;
    NSString        *iphoneStr;
}

@property (weak, nonatomic) IBOutlet UIButton *lookForPasswordBtn;
@property (strong, nonatomic) IBOutlet UIView *phoneBgView;
@property (strong, nonatomic) IBOutlet UIView *passwordBgView;
@property (strong, nonatomic) IBOutlet UIView *SMSCodeBgView;
@property (strong, nonatomic) IBOutlet UITextField *phoneTF;
@property (strong, nonatomic) IBOutlet UITextField *passwordTF;
@property (strong, nonatomic) IBOutlet UITextField *validateCodeTF;
@property (strong, nonatomic) IBOutlet UIButton *SMSButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iphoneLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iphoneRight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *IphoneTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btRight;


@end

@implementation MBLookForPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    timeout = 59;
    iphoneStr = @"";
    self.view.backgroundColor = [UIColor whiteColor];
//    self.SMSButton.layer.cornerRadius = 5.0;
//    self.SMSButton.clipsToBounds = YES;
    self.lookForPasswordBtn.layer.cornerRadius = 5.0;
    self.lookForPasswordBtn.clipsToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.view addGestureRecognizer:tap];
    [self setupNavBar];
    
    if (ISIPAD) {
        _iphoneLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _iphoneRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _IphoneTop.constant = 64+140*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _btRight.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;;
    }
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:_SMSButton.bounds byRoundingCorners:UIRectCornerBottomRight|UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = _SMSButton.bounds;
    layer.path = bezierPath.CGPath;
    _SMSButton.layer.mask = layer;
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    if (ISIPAD) {
        _iphoneLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _iphoneRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _IphoneTop.constant = 64+140*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _btRight.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;;
    }
}

- (void)hideKeyBoard{
    [_phoneTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
    [_validateCodeTF resignFirstResponder];
}
- (BOOL)validateInputIsGetSMSCode:(BOOL)getSMSCode{
    if ([_phoneTF.text isEqual:@""]) {
        NSLog(@"请输入手机号");
        [ErrorMessage showErrorMessage:@"请输入手机号" inView:self.view];
        return NO;
    }else{
        if (![_phoneTF.text isVAlidPhoneNumber]) {
            NSLog(@"手机号不合法");
            [ErrorMessage showErrorMessage:@"手机号不合法" inView:self.view];
            return NO;
        }
    }
    
    if (getSMSCode) {//获取验证码只需check手机号
        return YES;
    }
    
    if ([_passwordTF.text isEqual:@""]) {
        NSLog(@"请输入密码");
        [ErrorMessage showErrorMessage:@"请输入密码" inView:self.view];
        
        return NO;
    }else{
        if (_passwordTF.text.length<6) {
            NSLog(@"密码长度小于6位");
            [ErrorMessage showErrorMessage:@"密码长度小于6位" inView:self.view];
            
            return NO;
        }
    }
    if ([_validateCodeTF.text isEqual:@""]) {
        NSLog(@"请输入验证码");
        [ErrorMessage showErrorMessage:@"请输入验证码" inView:self.view];
        
        return NO;
    }
    return YES;
}

//找回密码
- (IBAction)lookForPasswordBtn:(id)sender {
    
    if (![self validateInputIsGetSMSCode:NO]) {
        return;
    }
    
    if (![codeStr isEqualToString:_validateCodeTF.text]) {
        [ErrorMessage showErrorMessage:@"验证码错误，请重试!" inView:self.view];
        return;
    }

    if (![iphoneStr isEqualToString:_phoneTF.text]) {
        [ErrorMessage showErrorMessage:@"手机号码不一致,请重试!" inView:self.view];
        return;
    }
    
    [[HTTPManager standerDefault]AFPostRequest:[NSString stringWithFormat:FORGET_PWD_URL_PATH,_phoneTF.text,[NSString stringWithMD5Encrypt:_passwordTF.text]] view:nil parameters: nil success:^(NSDictionary * json) {

        if ([json[@"ret_code"] integerValue]==0) {
            
            MBLookForPasswordLastController *registerLastVC = [[MBLookForPasswordLastController alloc] init];
            [self.navigationController pushViewController:registerLastVC animated:YES];
        }
        
    } failure:^(NSError *error) {
        
    }];
}

//获取验证码
- (IBAction)getSMSCode:(UIButton *)sender {
    if (![self validateInputIsGetSMSCode:YES]) {
        return;
    }

    NSString *url = [NSString stringWithFormat:VERIFICATION_PWD_URL_PATH,_phoneTF.text,@"SMS_22385060"];

    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        if ([str hasPrefix:@"InvalidSendSmsFrequency limit reaches"]) {
            //失败
            [ErrorMessage showErrorMessage:@"获取失败" inView:self.view];
        } else {
            //成功
            codeStr =  [str substringWithRange:NSMakeRange(str.length-7, 6)];
            iphoneStr = _phoneTF.text;
            [ErrorMessage showErrorMessage:@"短信已下发" inView:self.view];

            [self startTime];
        }
        
    }];
}

-(void)startTime{
    timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_SMSButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _SMSButton.userInteractionEnabled = YES;
                codeStr = @"";
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_SMSButton setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _SMSButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)setupNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackButton)];
    
}
//返回
-(void)navigationBackButton {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
